package com.alexb.tasksreport.resource;

import java.text.ParseException;

import javax.jdo.PersistenceManager;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.alexb.tasksreport.model.Task;
import com.alexb.tasksreport.util.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Path("/task/{id}")
public class TaskResource {

	@GET
	@Produces("application/json")
	public Task read(@PathParam("id") Long id) {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Task task;
		try {
			Key key = KeyFactory.createKey(Task.class.getSimpleName(), id);
			task = pm.getObjectById(Task.class, key);
		} finally {
			pm.close();
		}

		return task;
	}

	@POST
	@Produces("application/json")
	public Task update(@PathParam("id") Long id,
			@FormParam("label") String label,
			@FormParam("description") String description) throws ParseException {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Task task;
		try {
			Key key = KeyFactory.createKey(Task.class.getSimpleName(), id);
			task = pm.getObjectById(Task.class, key);
			task.setLabel(label);
			task.setDescription(description);
		} finally {
			pm.close();
		}

		return task;
	}

	@DELETE
	@Produces("application/json")
	public Boolean delete(@PathParam("id") Long id) {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Task task;
		try {
			Key key = KeyFactory.createKey(Task.class.getSimpleName(), id);
			task = pm.getObjectById(Task.class, key);
			pm.deletePersistent(task);
		} finally {
			pm.close();
		}

		return Boolean.TRUE;
	}

}
